//
//  UploadPhotosController.swift
//  QualityControlSystem
//
//  Created by dundun on 17/1/12.
//  Copyright © 2017年 com.mask. All rights reserved.
//

import UIKit
import Photos

protocol ImagePickingDelegate {
    func didFinishPickingImageInfo(asset: PHAsset, description: String)
}

class UploadPhotosController: UIViewController, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    @IBOutlet weak var uploadPhoto: UIImageView!
    @IBOutlet weak var photoDescribe: UITextView!
    @IBOutlet weak var commitBtn: UIButton!
    
    var delegate: ImagePickingDelegate?
    let asset: PHAsset
    
    init(asset: PHAsset) {
        self.asset = asset
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "上传照片"
        view.backgroundColor = Color.bgGray
        setupSubviews()
    }
    
    func setupSubviews() {
        let imageManager = PHImageManager()
        let options = PHImageRequestOptions()
        imageManager.requestImageData(for: asset, options: options, resultHandler: { data, string, orientation, info in
            self.uploadPhoto.image = UIImage(data: data!)
        })
        let gesture = UITapGestureRecognizer(target: self, action: #selector(uploadPhotoImageClicked(sender:)))
        uploadPhoto.addGestureRecognizer(gesture)
        uploadPhoto.layer.masksToBounds = true
        
        photoDescribe.delegate = self
        photoDescribe.text = "请输入照片说明（选填）"
        photoDescribe.textColor = UIColor.gray
        
        commitBtn.layer.borderWidth = 1.0
        commitBtn.layer.borderColor = UIColor.lightGray.cgColor
    }
    
    @IBAction func commitPhoto(_ sender: UIButton) {
        delegate?.didFinishPickingImageInfo(asset: asset, description: photoDescribe.text)
        navigationController?.popViewController(animated: true)
    }
    
    func uploadPhotoImageClicked(sender: UITapGestureRecognizer) {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.sourceType = .photoLibrary
            self.present(picker, animated: true, completion: nil)
        } else {
            let alert = UIAlertController.init(title: "提示", message: "读取相册错误", preferredStyle: .alert)
            let action = UIAlertAction.init(title: "确认", style: .default, handler: nil)
            alert.addAction(action)
            self.present(alert, animated: true, completion: nil)
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        uploadPhoto.image = image
        
        //select photo path
        let pickedURL = info[UIImagePickerControllerReferenceURL] as! URL
        let fetchResult: PHFetchResult = PHAsset.fetchAssets(withALAssetURLs: [pickedURL], options: nil)
        let asset: PHAsset = fetchResult.firstObject!
        PHImageManager.default().requestImageData(for: asset, options: nil) { (imageData, dataUTI, orientation, info) in
            let imageUrl = info!["PHImageFileURLKey"] as! URL
            print("路径：",imageUrl)
            print("文件名：",imageUrl.lastPathComponent)
        }
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    // MARK: - UITextViewDelegate
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.text == "请输入照片说明（选填）" {
            textView.text = ""
            textView.textColor = UIColor.black
        }
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.lengthOfBytes(using: String.Encoding.utf8) < 1 {
            textView.text = "请输入照片说明（选填）"
            textView.textColor = UIColor.gray
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
